package com.jiyun.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.jiyun.common.model.*;
import com.jiyun.common.vo.R;
import com.jiyun.fegin.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * @projectName: 2210A-project1
 * @package: com.jiyun.controller
 * @className: PlayLoadController
 * @author: 耿嘉军
 * @date: 2023/8/22 10:50
 * @version: 1.0
 */
@RestController
@RequestMapping("playLoad")
@Slf4j
public class PlayLoadController {

    @Autowired
    private PlayFegin playFegin;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CourseFegin courseFegin;

    @Autowired
    private GameFegin gameFegin;


    @Autowired
    private CatalogFegin catalogFegin;

    @Autowired
    private TagFegin tagFegin;

    @Autowired
    private TrainFegin trainFegin;

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("loginPlay")
    public R loginPlay(String username,String password){
        try {
            Play play = playFegin.playLoad(username, password);
            log.info("登录的play信息：{}",play);
            if (play!=null){
                HashMap<String, Object> map = new HashMap<>();
                map.put("pid",play.getPid());
                String token = JWTUtil.createToken(map, "1234".getBytes());
                redisTemplate.opsForHash().put("play",token, JSONUtil.toJsonStr(play));
                return R.ok(token);
            }else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @RequestMapping("findCourse")
    public R findCourse(){
        try {
            List<Course> courses = trainFegin.showCourseList();
            return R.ok(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @RequestMapping("addDian")
    public R addDian(Integer id){
        Course course = courseFegin.updateDian(id);
        return R.ok(course);
    }

    /**
     * 最新课程 通过sql 语句 order by id  获取前三条
     * @return
     */
    @RequestMapping("zuixincourse")
    public R zuixincourse(){
        try {
            List<Course> courses = courseFegin.zuixinCourse();
            return R.ok(courses);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 统计课程数量 通过用户查找 课程数量  一个人有多个课程 这里是用来一个字符串拼接做的一对多
     * @param request
     * @return ArrayList<Course>
     */
    @RequestMapping("countCourse")
    public R countCourse(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            List<Course> courses = courseFegin.courseList();
            ArrayList<Course> list = new ArrayList<>();
            for (Course cours : courses) {
                String[] split = cours.getUserId().split(",");
                for (String userid : split) {
                    if (userid.equals(play1.getPid()+"")){
                        List<Yiwc> yiwcs = catalogFegin.countYiwc(cours.getId(),play1.getPid());
                        int size = catalogFegin.catalogList().size();
                        float n = (float)yiwcs.size()/(float)size*100;
                        DecimalFormat df = new DecimalFormat("0");
                        String format = df.format(n);
                        cours.setBafb(format);
                        list.add(cours);
                    }
                }
            }
            return R.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * 统计竞赛的个数  一个人有多个竞赛 这里是用来一个字符串拼接做的一对多
     * @param request
     * @return List<Game>
     */
    @RequestMapping("countGame")
    public R countGame(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            ArrayList<Game> list = new ArrayList<>();
            List<Game> games = gameFegin.gameList();
            for (Game game : games) {
                if (game.getPlayids().contains(play1.getPid()+"")){
                    list.add(game);
                }
            }
            return R.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     *  统计培训 通过当前登录人 playId  在中间表 train_play中找到当前人有多少个培训
     * @param request
     * @return
     */
    @RequestMapping("countTrain")
    public R countTrain(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            ArrayList<TrainVO> trainVOS = new ArrayList<>();
            List<TrainPlay> trainPlays = trainFegin.trainPlayList();
            for (TrainPlay trainPlay : trainPlays) {
                if (trainPlay.getXpid().equals(play1.getPid())){
                    TrainDto dto = new TrainDto();
                    dto.setId(trainPlay.getXtrid());
                    PageInfo<TrainVO> byTrainVO = trainFegin.findByTrainVO(dto);
                    trainVOS.add(byTrainVO.getList().get(0));
                }
            }
            return R.ok(trainVOS);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * 统计 历史测验 [试卷]  通过培训找到试卷
     * 这个要通过 个人playId找到参加的培训 再通过培训找到所作 的试卷同时对试卷进行去重 因为会做到同一张试卷
     * @return  HashMap<Integer, PaperVO> map
     */
    @RequestMapping("countPaperList")
    public R countPaperList(HttpServletRequest request){
        String token = request.getHeader("token");
        String play = (String) redisTemplate.opsForHash().get("play", token);
        Play play1 = JSONUtil.toBean(play, Play.class);
        List<TrainPlay> trainPlays = trainFegin.trainPlayList();
        HashMap<Integer, PaperVO> map = new HashMap<>();
        for (TrainPlay trainPlay : trainPlays) {
            // 找到自己参加的 培训
            log.info("当前的培训与试卷的中间表：{}",trainPlay);
            if (trainPlay.getXpid().equals(play1.getPid())){
                // 通过培训 找到所作的试卷
                List<Paper> paperByTrainId = trainFegin.findPaperByTrainId(trainPlay.getXtrid());
                log.info("试卷paper：{}",paperByTrainId);
                for (Paper paper : paperByTrainId) {
                    PaperMc mc = new PaperMc();
                    mc.setPid(paper.getPid());
                    PageInfo<PaperVO> paperAll = paperFegin.findPaperAll(mc);
                    PaperVO paperVO = paperAll.getList().get(0);
                    map.put(paper.getPid(),paperVO);
                }
            }
        }
        return R.ok(map);
    }
    /**
     *  展示 team 战队的个数
     */
    @RequestMapping("countTeam")
    public R countTeam(HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            TeamVO vo = playFegin.findTeamVoByPlayId(play1.getPid());
            return R.ok(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }

    }

    /**
     * 展示竞赛   前端页面 ：Portal
     * @return List<Train>
     */
    @RequestMapping("showTrainAll")
    public R showTrainAll(){
        try {
            List<Train> trains = trainFegin.showTrainCountAll();
            return R.ok(trains);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 展示试卷  前端页面 ：Portal
     * @return  List<Paper>
     */
    @RequestMapping("findPaper")
    public R findPaper(){
        List<Paper> papers = trainFegin.showPaper();
        return R.ok(papers);
    }

    //课程的详情页面
    @RequestMapping("courseXiangQ")
    public R courseXiangQ(CourseMc mc){
        try {
            PageInfo<CourseVO> list = courseFegin.courseXiangQ(mc);
            return R.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 展示 标签
     * @return
     */
    @RequestMapping("showTag")
    public R showTag(){
        try {
            List<Tag> tags = tagFegin.showTag();
            return R.ok(tags);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 展示单个课程的信息
     * @param id
     * @return
     */
    @RequestMapping("findByCourseId")
    public R findByCourseId(Integer id){
        try {
            CourseMc mc = new CourseMc();
            mc.setId(id);
            PageInfo<CourseVO> pageInfo = courseFegin.courseXiangQ(mc);
            List<CourseVO> list = pageInfo.getList();
            return R.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 展示目录
     * @return
     */
    @RequestMapping("showCatalog")
    public R showCatalog(){
        R catalog0 = catalogFegin.findCatalog0(null);
        return catalog0;
    }

    /**
     * 统计全部的目录数量
     * @return
     */
    @RequestMapping("countCatalog")
    public R countCatalog(){
        int size = catalogFegin.catalogList().size();
        return R.ok(size);
    }

    /**
     * 统计已学的目录 通过课程courseId 与 当前人的PlayId
     * @param courseId
     * @param request
     * @return
     */
    @RequestMapping("coutYixue")
    public R coutYixue(Integer courseId,HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            List<Yiwc> yiwcs = catalogFegin.countYiwc(courseId,play1.getPid());
            return R.ok(yiwcs.size());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 课程表 的 目录的学习 一加一减
     * @param courseId
     * @param treeId
     * @param request
     * @return
     */
    @RequestMapping("xueorno")
    public R xueorno(Integer courseId,Integer treeId,HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            Yiwc yiwc= catalogFegin.findTree(courseId,play1.getPid(),treeId);
            redisTemplate.opsForHash().put("yiwc","playId",play1.getPid());
            redisTemplate.opsForHash().put("yiwc","courseId",courseId);
            redisTemplate.opsForHash().put("yiwc","treeId",treeId);
            redisTemplate.opsForHash().put("yiwc","yiwc",JSONUtil.toJsonStr(yiwc));
            //添加学习进度之前判断 是否已经学习 有则删除
            boolean b= catalogFegin.saveYiwc();
            if (b){
                return R.ok("学习成功");
            }else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * 竞赛的开始   展示tag
     */
    @RequestMapping("GameShowTag")
    public R GameShowTag(){
        List<Tag> tags = tagFegin.showTag();
        return R.ok(tags);
    }

    /**
     * 展示所有的竞赛信息 带条件摸查
     * @param dto 条件摸查
     * @return  PageInfo<GameVO> 实现分页效果
     */
    @RequestMapping("findGameAndTag")
    public R findGameAndTag(GameDto dto){
        PageInfo<GameVO> pageInfo = gameFegin.gameAndTag(dto);
        return R.ok(pageInfo);
    }

    /**
     * 展示 某个竞赛的具体信息 通过 gameId
     * @param gid
     * @return GameVO 前端所需要的具体数据
     */
    @RequestMapping("findGameById")
    public R findGameById(Integer gid){
        try {
            GameDto dto = new GameDto();
            dto.setGid(gid);
            PageInfo<GameVO> gameVOPageInfo = gameFegin.gameAndTag(dto);
            GameVO gameVO = gameVOPageInfo.getList().get(0);
            return R.ok(gameVO);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 展示 战队信息
     * @return 战队信息
     */
    @RequestMapping("GameshowTeam")
    public R GameshowTeam(){
        List<Team> teams = playFegin.GameshowTeam();
        return R.ok(teams);
    }

    /**
     *  进行添加战队 通过 gameId ，战队Id ，当前人 playId
     * @param gid
     * @param teamId
     * @param request
     * @return 是否添加成功
     */
    @RequestMapping("findGameAndTeam")
    public R findGameAndTeam(Integer gid,Integer teamId,HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            boolean b = gameFegin.saveTeamAndGame(play1.getPid(), gid,teamId);
            log.info("saveTeam:{}",b);
            if (b){
                return R.ok(b);
            }else {
                return R.error();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     *  通过 gameId 和 登陆人playId 查询 是 否已经报名过了
     * @param gid
     * @param request
     * @return
     */
    @RequestMapping("findGameTeam")
    public R findGameTeam(Integer gid,HttpServletRequest request){
        String token = request.getHeader("token");
        String play = (String) redisTemplate.opsForHash().get("play", token);
        Play play1 = JSONUtil.toBean(play, Play.class);
        GameTeam gameTeam= gameFegin.findByPlay(gid,play1.getPid());
        if (gameTeam==null){
            return R.ok("1");
        }else {
            return R.ok("2");
        }
    }
    /**
     * 开始竞赛
     */

    @RequestMapping("findByBeginTrain")
    public R findByBeginTrain(Integer gameId,HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            GameTeam byPlay = gameFegin.findByPlay(gameId, play1.getPid());
            BeginTrain beginTrain = gameFegin.gameAndTeamAndPlayAndTag(gameId, byPlay.getTeamId(), play1.getPid());
            return R.ok(beginTrain);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 查找试卷 通过竞赛id查询试卷
     */
    @RequestMapping("findPaperByGameId")
    public R findPaperByGameId(Integer gameId){
        List<Paper> gamePaper = gameFegin.findGamePaper(gameId);
        return R.ok(gamePaper);
    }

    @Autowired
    private PaperFegin paperFegin;
    /**
     * 查找试题 通过课程id
     */
    @RequestMapping("findByQuestion")
    public R findByQuestion(Integer paperId){
        try {
            List<Question> questionByPaper = paperFegin.findQuestionByPaper(paperId);
            return R.ok(questionByPaper);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 开始培训 【培训列表】
     */
    @RequestMapping("findTrainList")
    public R findTrainList(TrainDto dto){
        try {
            PageInfo<TrainVO> byTrainVO = trainFegin.findByTrainVO(dto);
            return R.ok(byTrainVO);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 通过trainId 展示单个培训[train]内容
     */
    @RequestMapping("findTrainById")
    public R findTrainById(Integer trainId){
        try {
            TrainDto dto = new TrainDto();
            dto.setId(trainId);
            PageInfo<TrainVO> vo = trainFegin.findByTrainVO(dto);
            TrainVO trainVO = vo.getList().get(0);
            return R.ok(trainVO);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 通过 trainId 培训id查找课程
     */
    @RequestMapping("findCourseByTrainId")
    public R findCourseByTrainId(Integer trainId){
        List<Course> courseBytrainId = trainFegin.findCourseBytrainId(trainId);
        return R.ok(courseBytrainId);
    }

    /**
     * 向前台 发送登录人的 Id
     * @param request
     * @return playId
     */
    @RequestMapping("findPlayId")
    public R findPlayId(HttpServletRequest request){
        String token = request.getHeader("token");
        String play = (String) redisTemplate.opsForHash().get("play", token);
        Play play1 = JSONUtil.toBean(play, Play.class);
        return R.ok(play1);
    }

    @RequestMapping("findPaperByTrainId")
    public R findPaperByTrainId(Integer trainId){
        try {
            List<Paper> papers = trainFegin.findPaperByTrainId(trainId);
            return R.ok(papers);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     * 测试列表  展示所有试卷
     */
    @RequestMapping("findAllPaper")
    public R findAllPaper(PaperMc dto){
        try {
            PageInfo<PaperVO> paperAll = paperFegin.findPaperAll(dto);
            return R.ok(paperAll);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    /**
     *  每个试卷中的 试题
     */
    @RequestMapping("findQuestionByPaperId")
    public R findQuestionByPaperId(Integer paperId){
        try {
            List<Question> questionByPaper = paperFegin.findQuestionByPaper(paperId);
            return R.ok(questionByPaper);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @RequestMapping("updatePassword")
    public R updatePassword(String password,HttpServletRequest request){
        try {
            String token = request.getHeader("token");
            String play = (String) redisTemplate.opsForHash().get("play", token);
            Play play1 = JSONUtil.toBean(play, Play.class);
            boolean b = playFegin.updatePlayPassword(play1.getPid()+"", password);
            return R.ok(b);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }




}
